var http = require('http');
var express = require('express');
var socketio = require('socket.io');
var routes = require('./routes.js');
var path = require('path');

var app = express();
var server = http.createServer(app);
server.listen(80);

var index = express.Router();
    index.get('/', routes.index);
	index.get('/index.html', routes.index);

var env = process.env.NODE_ENV || 'development';
if ('development' == env) {
    // configure stuff here
    app.set('view engine', 'ejs')
    app.use('/', index);
    //app.use('/form', form);
    app.use(express.static(path.join(__dirname, 'public')));
};

var io = socketio.listen(server);
var names = [];

io.sockets.on('connection', function(socket){
    socket.on('login', function(name){
	    for(var i = 0;i<names.length;i++){
		    if(names[i] == name){
			    socket.emit('duplicate');
				return;
			}
		}
		names.push(name);
		io.sockets.emit('login', name);
		io.sockets.emit('sendClients', names);
	});
	socket.on('chat', function(data){
	    io.sockets.emit('chat', data);
	});
	socket.on('logout', function(name){
	    for(var i = 0;i<names.length;i++){
		    if(names[i] == name){
			    names.splice(i, 1);
			}
		}
		socket.broadcast.emit('logout', name);
		io.sockets.emit('sendClients', names);
    });
});


//app.listen(80);
